package com.rockblade.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;
import com.baomidou.mybatisplus.generator.keywords.PostgreSqlKeyWordsHandler;
import com.rockblade.generator.utils.GeneratorUtils;
import com.rockblade.generator.utils.YamlReaderUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Scanner;

/**
 * @author LOST.yuan
 */
public class GeneratorApplication {

    public static void main(String[] args) {
        YamlReaderUtils yamlReaderUtils = YamlReaderUtils.instance;
        GeneratorUtils generatorUtils = GeneratorUtils.getInstance();
        //1.数据库配置
        DataSourceConfig.Builder dataSourceConfigBuilder = new DataSourceConfig.Builder((String) yamlReaderUtils.getValueByKey("spring.datasource.url"),
                (String) yamlReaderUtils.getValueByKey("spring.datasource.username"),
                (String) yamlReaderUtils.getValueByKey("spring.datasource.password"))
                .dbQuery(new PostgreSqlQuery())
                .typeConvert(new PostgreSqlTypeConvert())
                .keyWordsHandler(new PostgreSqlKeyWordsHandler());

        //1.1代码生成器
        FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(dataSourceConfigBuilder);
        //2.全局配置
        generatorUtils.setGlobalConfig(fastAutoGenerator, yamlReaderUtils);
        //3.包配置
        generatorUtils.setPackageConfig(fastAutoGenerator, yamlReaderUtils);
        //4.模板配置
        generatorUtils.setTemplateConfig(fastAutoGenerator);
        //5.生成代码
        //5.1设置需要生成的表名
        fastAutoGenerator.strategyConfig(builder -> builder.addInclude(scanner("表名，多个英文逗号分割").split(",")));
        //5.2设置策略
        generatorUtils.setStrategyConfig(fastAutoGenerator, yamlReaderUtils);
        //(PLUS)6.移动From类到指定文件夹中
        fastAutoGenerator.execute();
        generatorUtils.moveFromFiles(yamlReaderUtils);

    }


    /**
     * 命令行输入表名
     * @param tip
     * @return
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

}
